// 用于共享用户认证信息
import { createContext, useContext, useState } from "react"

const AuthContext = createContext() // 创建一个上下文对象

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(() => {
        const stored = localStorage.getItem("auth")
        return stored ? JSON.parse(stored) : { token: null, roles: [] }
    })

    const login = (data) => {
        setUser(data)
        localStorage.setItem("auth", JSON.stringify(data))
    }

    const logout = () => {
        setUser({ token: null, roles: [] })
        localStorage.removeItem("auth")
    }

    return <AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>
}

export const useAuth = () => useContext(AuthContext)
